<?php
namespace Duobao\Controller;
use Duobao\Controller\LogController as Mylog;
use Duobao\Model\PingModel as Ping;

class PingController extends ControllerBase{
    /**
     * 默认
     */
    public function index()
    {
        echo "<!--hi , i'm from " . MODULE_NAME . "~" . APP_STATUS, "-->";
    }

    /**
     * 主要用于支付宝，网银支付的回调，ping++
     * 的webhooks
     */
    public function notify(){
        $event = json_decode(file_get_contents("php://input"));
        $raw_data = file_get_contents('php://input');

        $headers = getRequestHeaders();
        // 签名在头部信息的 x-pingplusplus-signature 字段
        $signature = isset($headers['X-Pingplusplus-Signature']) ? $headers['X-Pingplusplus-Signature'] : NULL;
        #公钥：
        $public_key_path = C('public_key_path');
        #验证签名
        $result = verify_signature($raw_data, $signature, $public_key_path);
        if ($result === 1) {
            // 验证通过
        } elseif ($result === 0) {
            http_response_code(400);
            echo 'verification failed';
            exit;
        } else {
            http_response_code(400);
            echo 'verification error';
            exit;
        }

        // 对异步通知做处理
        if (!isset($event->type)) {
            header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
            exit("fail");
        }
        switch ($event->type) {
            case "charge.succeeded":
                #处理订单
                $handler_result = $this->handler_oreder($event);

                if($handler_result == TRUE){
                    header($_SERVER['SERVER_PROTOCOL'] . ' 200 OK');
                }else {
                    header($_SERVER['SERVER_PROTOCOL'] . ' 200 OK');
                    echo "处理订单失败，订单编号：".$event->data->object->order_no."---ping流水号".$event->data->object->transaction_no;
                }
                  break;
            case "refund.succeeded":
                // 开发者在此处加入对退款异步通知的处理代码
                header($_SERVER['SERVER_PROTOCOL'] . ' 200 OK');
                break;
            default:
                header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
                break;
        }
    }

    private function handler_oreder($event){
        #获取event中的order_no和paid和amount
        $order_no = $event->data->object->order_no;
        $paid = $event->data->object->paid;
        $amount = $event->data->object->amount;
        $transaction_no = $event->data->object->transaction_no;
        if($paid){
            $ping = new Ping();
            #Mylog::write('进入ping处理订单');
            $result = $ping->ping_notify($order_no,$amount,$transaction_no);

            if($result == TRUE){
                return TRUE;
            }else{
                return FALSE;
            }
        }else{
            Mylog::write('paid为false');
            return FALSE;
        }
    }
}